import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios';
import {authRoutes} from '../router';
axios.defaults.baseURL = "http://localhost:3000";
axios.interceptors.response.use(res => res.data);
Vue.use(Vuex)

const getAuths = (menuList) => {
  console.log(1);
  let menu = JSON.parse(JSON.stringify(menuList));
  let index = 0;
  let arr = [];
  let current;
  while (current = menu[index]) {
    arr.push(current.auth);
    if (current.children) {
      menu = menu.concat(current.children);
    }
    index++;
  }
  return arr;
}
const formateList = (authRoutes,auths)=>{
  return authRoutes.filter(route=>{
      if(auths.includes(route.name)){
          if(route.children){
           route.children =  formateList(route.children,auths);
          }
          return true;
      }
      
  })
}
export default new Vuex.Store({
  state: {
    hasPermission: false,
    menuList: [],
    btnPermission:{
      edit:true,
      add:true
    }
  },
  mutations: {
    setMenu(state, menuList) {
      state.menuList = menuList;
    },
    setPermission(state){
        state.hasPermission = true
    }
  },
  actions: {
    async getNewRoute({ commit }) {
      let { menuList } = await axios.get('/roleAuth');
      commit('setMenu', menuList);
      let auths = getAuths(menuList);
      console.log(auths);
      let needRoutes = formateList(authRoutes,auths);
       commit('setPermission');
       return needRoutes
    }
  },
  modules: {
  }
})
